package com.csf.context;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * TODO ADD DESCRIPTION
 * Date: 2018/8/28
 * Time: 17:11
 *
 * @author chenshf
 */
public class ClassPathXmlApplicationContext implements ApplicationContext {

    public ClassPathXmlApplicationContext(String xmlPath) {
        loadBean(xmlPath);
    }

    private Map<String,Object> beansMap = new HashMap<>();

    @Override
    public Object getBean(String beanId) {
        return beansMap.get(beanId);
    }

    public void loadBean(String xmlPath){
        //根据xml解析
        InputStream resourceAsStream = ClassPathXmlApplicationContext.class.getClassLoader().getResourceAsStream(xmlPath);

        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(resourceAsStream);
            evalElement(document);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    /**
     * 解析dom
     * @param document
     */
    private void evalElement(Document document) {
        Element rootElement = document.getRootElement();
        if("beans".equals(rootElement.getName())){
            List<Element> elements = rootElement.elements();
            for(Element element:elements){
                String beanId = element.attributeValue("id");
                String aClass = element.attributeValue("class");
                try {
                    Class<?> c = Class.forName(aClass);
                    Object o = c.newInstance();
                    List<Element> elements1=element.elements();
                    for (Element element1:elements1){
                        String field = element1.attributeValue("name");
                        String value = element1.attributeValue("value");
                        Field declaredField = c.getDeclaredField(field);
                        declaredField.setAccessible(true);
                        declaredField.set(o,value);
                    }
                    beansMap.put(beanId,o);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }

            }
        }else {
            System.out.println("xml格式有误====");
        }
    }
}
